<template>
  <div>
    <el-dialog
      :visible.sync="coverImgDialogFormVisible"
      :modal-append-to-body="true"
      :append-to-body="true"
      title="封面和商品图片"
      width="800px"
    >
      <el-form
        ref="stockDialogRulesForm"
        :model="goodsCoverData"
        class="dialog-form"
        label-position="left"
        label-width="120px"
      >
        <el-form-item label="封面" prop="cover">
          <el-upload
            :action="UPLOAD_URL"
            :headers="getHeaders()"
            :show-file-list="false"
            :on-success="handleUploadCoverSuccess"
            :before-upload="beforeAvatarUpload"
            class="avatar-uploader"
          >
            <img v-if="goodsCoverData.cover" :src="goodsCoverData.cover|imgUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="商品图片" prop="img_srcs">
          <xd-upload v-model="goodsCoverData.img_srcs" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sureSelectPic">确定</el-button>
      </div>
    </el-dialog>
    <template v-if="goodsRules.length">
      <el-card v-for="(goodRule,index) in goodsRules" :key="index" class="box-card">
        <div slot="header" class="clearfix">
          <el-input
            v-model="goodRule.title"
            :ref="'goodsRuleInput'+index"
            placeholder="请输入商品规格名称(比如颜色)"
            style="width:250px;"
          />&nbsp;&nbsp;&nbsp;&nbsp;
          <i
            class="el-icon-close close-btn right-icon"
            @click="removeRule(index)"
          />
        </div>
        <div v-for="(item,yindex) in goodRule.items" :key="yindex" class="el-tag-wrapper">
          <el-tag
            :disable-transitions="false"
            closable
            class="my-el-tag"
            @click="editRuleItem(item)"
            @close="handleClose(index,yindex)"
          >{{ item.title }}</el-tag>
        </div>
        <div class="el-tag-wrapper">
          <el-input
            v-show="goodRule.inputVisible"
            v-model="goodRule.inputValue"
            :ref="'saveTagInput'+index"
            :focus="true"
            class="input-new-tag"
            size="small"
            @keyup.enter.native="handleInputConfirm(index)"
            @blur="handleInputConfirm(index)"
          />
          <el-button
            v-if="!goodRule.inputVisible && goodRule.items.length<9"
            class="button-new-tag"
            size="small"
            @click="showInput(index)"
          >
            +
            添加规格
          </el-button>
        </div>
      </el-card>
    </template>
    <template v-else-if="defaultSku">
      <div class="default-sku">
        <el-form
          ref="dataForm2"
          :rules="rules"
          :model="defaultSku"
          label-position="left"
          label-width="120px"
        >
          <el-row :gutter="18">
            <el-col :span="20">
              <el-row :gutter="20">
                <el-col :span="18">
                  <el-form-item label="商品名称" prop="title">
                    <el-input v-model="defaultSku.title" placeholder="请输入商品名称" />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="商品编码" prop="goods_no">
                    <el-input v-model="defaultSku.goods_no" placeholder="请输入商品编码" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="商品价格" prop="price">
                    <!-- :disabled="isEditingDefaultSku" -->
                    <el-input-number v-model="defaultSku.price" placeholder="请输入微信价" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="会员价格" prop="member_price">
                    <el-input-number v-model="defaultSku.member_price" placeholder="请输入积分价" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="重量(克)" prop="weight">
                    <el-input-number v-model="defaultSku.weight" placeholder="请输入重量(克)" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="库存" prop="stock">
                    <el-input-number
                      :disabled="isEditingDefaultSku"
                      v-model="defaultSku.stock"
                      placeholder="请输入库存"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="预警库存" prop="alert_stock">
                    <el-input-number
                      v-model="defaultSku.alert_stock"
                      placeholder="请输入预警库存"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="分享购买优惠" prop="share_discount">
                    <el-input-number v-model="defaultSku.share_discount" placeholder="分享购买优惠" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="推广佣金" prop="first_recommender_award">
                    <el-input-number
                      v-model="defaultSku.first_recommender_award"
                      placeholder="推广佣金"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="锁定佣金" prop="first_recommender_award">
                    <el-input-number v-model="defaultSku.recommender_award" placeholder="锁定佣金" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="4">
              封面与商品图片
              <div class="avatar-uploader-3" @click="showPicPickerDialog(-1)">
                <img v-if="defaultSku.cover" :src="defaultSku.cover|imgUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </template>
    <el-button
      v-if="goodsRules.length<3"
      type="primary"
      size="small"
      icon="el-icon-plus"
      @click="addNewGoodRule"
    >添加商品规格</el-button>
    <div v-if="hasValidRules" class="price-and-stock">
      <table>
        <thead>
          <tr class="batch">
            <td :colspan="hasValidRules" rowspan="2">批量修改</td>
            <td width="110">商品价格</td>
            <td width="110">会员价格</td>
            <td width="110">库存</td>
            <td width="110">重量(克)</td>
            <td width="110">分享优惠</td>
            <td width="110">推广佣金</td>
            <td width="110">锁定佣金</td>
            <td width="110">预警库存</td>
            <td colspan="3" rowspan="2" />
          </tr>
          <tr class="batch">
            <td>
              <el-input-number v-model="batchPrice" :min="0" class="numberbox" size="mini" />
            </td>
            <td>
              <el-input-number v-model="batchPoints" :min="0" class="numberbox" size="mini" />
            </td>
            <td>
              <el-input-number v-model="batchStock" :min="0" class="numberbox" size="mini" />
            </td>
            <td>
              <el-input-number v-model="batchWeight" :min="0" class="numberbox" size="mini" />
            </td>
            <td>
              <el-input-number v-model="batchShareDiscount" :min="0" class="numberbox" size="mini" />
            </td>
            <td>
              <el-input-number
                v-model="batchFirstRecommenderAward"
                :min="0"
                class="numberbox"
                size="mini"
              />
            </td>
            <td>
              <el-input-number
                v-model="batchRecommenderAward"
                :min="0"
                class="numberbox"
                size="mini"
              />
            </td>
            <td>
              <el-input-number v-model="batchalertStock" :min="0" class="numberbox" size="mini" />
            </td>
          </tr>
          <tr>
            <template v-for="(goodRule,index) in goodsRules">
              <th v-if="goodRule.items && goodRule.items.length" :key="index">{{ goodRule.title }}</th>
            </template>
            <th colspan="7">商品名称</th>
            <th colspan="1">商品编码</th>
            <th width="90">商品图片</th>
            <th width="70">状态</th>
            <th width="70">默认规格</th>
          </tr>
        </thead>
        <tbody>
          <template v-for="(row,index) in goodsRulePrices">
            <tr :key="index">
              <template v-for="(value,field) in row">
                <td v-if="value.rowSpan" :key="field" :rowspan="value.rowSpan">{{ value.title }}</td>
              </template>
              <td :class="{disabled_tr:!enabledMap[row._key]}" colspan="7">
                <el-input
                  :disabled="!enabledMap[row._key]"
                  v-model="titleMap[row._key]"
                  class="goods-title"
                  placeholder="请输入商品名称"
                  size="mini"
                />
              </td>
              <td :class="{disabled_tr:!enabledMap[row._key]}" colspan="1">
                <el-input
                  :disabled="!enabledMap[row._key]"
                  v-model="goodsNoMap[row._key]"
                  type="text"
                  class="goods-title"
                  placeholder="请输入商品编码"
                  size="mini"
                />
              </td>
              <td :class="{disabled_tr:!enabledMap[row._key]}" rowspan="3">
                <div
                  class="avatar-uploader-3"
                  @click="enabledMap[row._key] && showPicPickerDialog(row._key)"
                >
                  <img v-if="coverMap[row._key]" :src="coverMap[row._key]|imgUrl" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon" />
                </div>
              </td>
              <td rowspan="3">
                <el-checkbox v-model="enabledMap[row._key]">上架</el-checkbox>
              </td>
              <td rowspan="3">
                <el-radio
                  v-model="defaultMap[row._key]"
                  :label="true"
                  @change="changeDefaultSetting(row._key)"
                >默认</el-radio>
              </td>
            </tr>
            <tr :key="index+'_1'" :class="{disabled_tr:!enabledMap[row._key]}">
              <td width="110">商品价格</td>
              <td width="110">会员价格</td>
              <td width="110">库存</td>
              <td width="110">重量(克)</td>
              <td width="110">分享优惠</td>
              <td width="110">推广佣金</td>
              <td width="110">锁定佣金</td>
              <td width="110">预警库存</td>
            </tr>
            <tr :key="index+'_2'" :class="{disabled_tr:!enabledMap[row._key]}">
              <td>
                <el-input-number
                  :disabled="!enabledMap[row._key] || (editableMap[row._key] && !isAdmin())"
                  v-model="priceMap[row._key]"
                  :min="0"
                  class="numberbox"
                  size="mini"
                />
              </td>
              <td>
                <el-input-number
                  :disabled="!enabledMap[row._key] || (editableMap[row._key] && !isAdmin())"
                  v-model="memberPriceMap[row._key]"
                  :min="0"
                  class="numberbox"
                  size="mini"
                />
              </td>
              <td>
                <el-input-number
                  :disabled="!enabledMap[row._key] || editableMap[row._key]"
                  v-model="stockMap[row._key]"
                  :min="0"
                  class="numberbox"
                  size="mini"
                />
              </td>
              <td>
                <el-input-number
                  :disabled="!enabledMap[row._key] || editableMap[row._key]"
                  v-model="weightMap[row._key]"
                  :min="0"
                  class="numberbox"
                  size="mini"
                />
              </td>
              <td>
                <el-input-number
                  :disabled="!enabledMap[row._key] || editableMap[row._key]"
                  v-model="shareDiscountMap[row._key]"
                  :min="0"
                  class="numberbox"
                  size="mini"
                />
              </td>
              <td>
                <el-input-number
                  :disabled="!enabledMap[row._key] || editableMap[row._key]"
                  v-model="firstRecommenderAwardMap[row._key]"
                  :min="0"
                  class="numberbox"
                  size="mini"
                />
              </td>
              <td>
                <el-input-number
                  :disabled="!enabledMap[row._key] || editableMap[row._key]"
                  v-model="recommenderAwardMap[row._key]"
                  :min="0"
                  class="numberbox"
                  size="mini"
                />
              </td>
              <td>
                <el-input-number
                  :disabled="!enabledMap[row._key] || (editableMap[row._key] && !isAdmin())"
                  v-model="alertStockMap[row._key]"
                  :min="0"
                  class="numberbox"
                  size="mini"
                />
              </td>
            </tr>
          </template>
        </tbody>
      </table>
    </div>
  </div>
</template>
<script>
import xdUploadVue from "../components/xdUpload.vue";
export default {
  components: {
    "xd-upload": xdUploadVue
  },
  data() {
    return {
      enabledMap: {},
      defaultMap: {},
      editableMap: {},
      batchGoodsNo: "",
      batchMarketPrice: 0,
      batchPoints: 0,
      isEditingDefaultSku: false,
      goodsCoverData: {
        cover: "",
        img_srcs: ""
      },
      batchStock: 0,
      batchWeight: 0,
      batchShareDiscount: 0,
      batchFirstRecommenderAward: 0,
      batchRecommenderAward: 0,
      batchalertStock: 0,
      imgSrcsMap: {},
      batchPrice: 0,
      coverImgDialogFormVisible: false,
      goodsRules: [],
      memberPriceMap: {},
      // marketPriceMap: {},
      titleMap: {},
      firstRecommenderAwardMap: {},
      recommenderAwardMap: {},
      shareDiscountMap: {},
      defaultSku: null,
      coverMap: {},
      priceMap: {},
      stockMap: {},
      weightMap: {},
      alertStockMap: {},
      goodsNoMap: {},
      // barCodeMap: {},
      rules: {
        title: [
          {
            required: true,
            message: "商品名称不能为空",
            trigger: "change"
          },
          {
            max: 60,
            message: "商品名称不能大于60个字",
            trigger: "change"
          }
        ],
        price: [
          {
            required: true,
            message: "商品价格不能为空",
            trigger: "change"
          }
        ],
        weight: [
          {
            required: true,
            message: "商品重量不能为空",
            trigger: "change"
          }
        ],
        first_recommender_award: [
          {
            required: true,
            message: "推广佣金不能为空",
            trigger: "change"
          }
        ],
        recommender_award: [
          {
            required: true,
            message: "锁定佣金不能为空",
            trigger: "change"
          }
        ],
        share_discount: [
          {
            required: true,
            message: "分享购买优惠不能为空",
            trigger: "change"
          }
        ],
        member_price: [
          {
            required: true,
            message: "会员价格不能为空",
            trigger: "change"
          }
        ],

        goods_no: [
          {
            required: true,
            message: "商品编码不能为空",
            trigger: "change",
            max: 60
          }
        ],

        stock: [
          {
            required: true,
            message: "商品库存不能为空",
            trigger: "change"
          }
        ],

        alert_stock: [
          {
            required: true,
            message: "警戒库存不能为空",
            trigger: "change"
          }
        ]
      }
    };
  },
  computed: {
    hasValidRules() {
      let rt = 0;
      this.goodsRules.forEach(el => {
        if (el.items && el.items.length > 0) {
          rt++;
        }
      });
      return rt;
    },
    goodsRulePrices() {
      let rowCount = 0;
      for (let i = 0; i < this.goodsRules.length; i++) {
        if (this.goodsRules[i].items.length > 0) {
          if (rowCount === 0) {
            rowCount = 1;
          }
          rowCount *= this.goodsRules[i].items.length;
        }
      }
      const rows = [];
      if (rowCount > 0) {
        // rowCount*=2;
        for (let i = 0; i < rowCount; i++) {
          rows.push([]);
        }
        let groupCount = 1; // 分组
        let colIndex = 0;
        for (let i = 0; i < this.goodsRules.length; i++) {
          const rule = this.goodsRules[i];
          const items = rule.items;
          if (items && items.length) {
            const rowSpan = rowCount / items.length / groupCount;
            const groupSize = rowCount / groupCount;
            for (let g = 0; g < groupCount; g++) {
              for (let j = 0; j < items.length; j++) {
                for (let k = 0; k < rowSpan; k++) {
                  rows[groupSize * g + j * rowSpan + k][colIndex] = {
                    title: items[j].title,
                    index: j,
                    rowSpan: k === 0 ? rowSpan * 3 : 0
                  };
                }
              }
            }
            groupCount *= items.length;
            colIndex++;
          }
        }
      }
      this.resetMap();
      rows.forEach(row => {
        const idx = this.parse2Key(row);
        row._key = idx;
        this.goodsNoMap[idx] || this.$set(this.goodsNoMap, idx, "");
        this.coverMap[idx] || this.$set(this.coverMap, idx, "");
        this.imgSrcsMap[idx] || this.$set(this.imgSrcsMap, idx, "");
        this.stockMap[idx] || this.$set(this.stockMap, idx, this.batchStock);
        this.weightMap[idx] || this.$set(this.weightMap, idx, this.batchWeight);
        this.priceMap[idx] || this.$set(this.priceMap, idx, this.batchPrice);
        this.shareDiscountMap[idx] ||
          this.$set(this.shareDiscountMap, idx, this.batchShareDiscount);
        this.firstRecommenderAwardMap[idx] ||
          this.$set(
            this.firstRecommenderAwardMap,
            idx,
            this.batchFirstRecommenderAward
          );
        this.recommenderAwardMap[idx] ||
          this.$set(this.recommenderAwardMap, idx, this.batchRecommenderAward);
        this.memberPriceMap[idx] ||
          this.$set(this.memberPriceMap, idx, this.batchPoints);
        this.alertStockMap[idx] ||
          this.$set(this.alertStockMap, idx, this.batchalertStock);
        this.enabledMap.hasOwnProperty(idx) ||
          this.$set(this.enabledMap, idx, true);
        if (!this.defaultMap.hasOwnProperty(idx)) {
          this.$set(this.defaultMap, idx, false);
        }
      });
      if (this.defaultMap) {
        let hasDefault = false;
        let firstKey = "";
        Object.keys(this.defaultMap).forEach(key => {
          if (!firstKey) {
            firstKey = key;
          }
          if (this.defaultMap[key] === true) {
            hasDefault = true;
          }
        });
        if (!hasDefault) {
          this.$set(this.defaultMap, firstKey, true);
          console.log(this.defaultMap);
        }
      }

      return rows;
    }
  },
  // model: {
  //   prop: "goodsRuleValues",
  //   event: "changeGoodsRuleValues"
  // },
  // props: {
  //   goodsRuleValues: null
  // },
  watch: {
    // goodsRuleValues() {
    //   this.initData();
    // },
    batchPrice() {
      for (const key in this.priceMap) {
        this.priceMap[key] = this.batchPrice;
      }
    },
    batchMarketPrice() {
      for (const key in this.marketPriceMap) {
        this.marketPriceMap[key] = this.batchMarketPrice;
      }
    },
    batchPoints() {
      for (const key in this.memberPriceMap) {
        this.memberPriceMap[key] = this.batchPoints;
      }
    },
    batchStock() {
      for (const key in this.stockMap) {
        this.stockMap[key] = this.batchStock;
      }
    },
    batchWeight() {
      for (const key in this.weightMap) {
        this.weightMap[key] = this.batchWeight;
      }
    },
    batchShareDiscount() {
      for (const key in this.shareDiscountMap) {
        this.shareDiscountMap[key] = this.batchShareDiscount;
      }
    },
    batchFirstRecommenderAward() {
      for (const key in this.firstRecommenderAwardMap) {
        this.firstRecommenderAwardMap[key] = this.batchFirstRecommenderAward;
      }
    },
    batchRecommenderAward() {
      for (const key in this.recommenderAwardMap) {
        this.recommenderAwardMap[key] = this.batchRecommenderAward;
      }
    },
    batchalertStock() {
      for (const key in this.alertStockMap) {
        this.alertStockMap[key] = this.batchalertStock;
      }
    }
    // ,
    // batchGoodsNo() {
    //   for (let key in this.goodsNoMap) {
    //       this.goodsNoMap[key] = this.batchGoodsNo;
    //   }
    // }
  },
  methods: {
    resetMap() {
      this.defaultMap = {};
      this.enabledMap = {};
    },
    changeDefaultSetting(key) {
      console.log(arguments);
      const rows = this.goodsRulePrices;
      rows.forEach(row => {
        const idx = this.parse2Key(row);
        if (idx !== key) {
          this.$set(this.defaultMap, idx, false);
        }
      });
    },
    parse2Key(row) {
      const data = {};
      for (let i = 0; i < row.length; i++) {
        data[this.goodsRules[i].title] = row[i].title;
      }
      return JSON.stringify(data);
    },
    editRuleItem(item) {
      console.log(item);
    },
    showPicPickerDialog(idx) {
      this.coverImgDialogFormVisible = true;
      if (idx < 0) {
        this.goodsCoverData.cover = this.defaultSku.cover;
        this.goodsCoverData.img_srcs = this.defaultSku.img_srcs;
      } else {
        this.goodsCoverData.cover = this.coverMap[idx];
        this.goodsCoverData.img_srcs = this.imgSrcsMap[idx];
      }
      this.goodsCoverData.idx = idx;
    },
    valid() {
      if (!this.$refs["dataForm2"]) {
        return true;
      }
      let rt = false;
      this.$refs["dataForm2"].validate(valid => {
        if (valid) {
          rt = true;
        }
      });
      return rt;
    },
    sureSelectPic() {
      this.coverImgDialogFormVisible = false;
      if (this.goodsCoverData.idx < 0) {
        this.defaultSku.cover = this.goodsCoverData.cover;
        this.defaultSku.img_srcs = this.goodsCoverData.img_srcs;
      } else {
        this.coverMap[this.goodsCoverData.idx] = this.goodsCoverData.cover;
        this.imgSrcsMap[this.goodsCoverData.idx] = this.goodsCoverData.img_srcs;
      }
    },
    getData() {
      const skuList = [];
      const rowCount = this.goodsRulePrices.length;
      if (rowCount > 0) {
        for (let i = 0; i < rowCount; i++) {
          const row = this.goodsRulePrices[i];
          const key = this.parse2Key(row);
          if (!this.enabledMap[key]) {
            continue;
          }
          skuList.push({
            goods_no: this.goodsNoMap[key] || "",
            price: this.priceMap[key] || 0,
            member_price: this.memberPriceMap[key] || 0,
            sale_pros: key,
            stock: this.stockMap[key] || 0,
            weight: this.weightMap[key] || 0,
            alert_stock: this.alertStockMap[key] || 0,
            cover: this.coverMap[key] || "",
            img_srcs: this.imgSrcsMap[key] || "",
            is_default: this.defaultMap[key] ? 1 : 0,
            title: this.titleMap[key] || "",
            first_recommender_award: this.firstRecommenderAwardMap[key] || "",
            recommender_award: this.recommenderAwardMap[key] || "",
            share_discount: this.shareDiscountMap[key] || ""
          });
        }
      } else {
        skuList.push({
          goods_no: this.defaultSku.goods_no,
          price: this.defaultSku.price,
          member_price: this.defaultSku.member_price,
          weight: this.defaultSku.weight,
          sale_pros: "",
          stock: this.defaultSku.stock,
          alert_stock: this.defaultSku.alert_stock,
          cover: this.defaultSku.cover,
          share_discount: this.defaultSku.share_discount,
          first_recommender_award: this.defaultSku.first_recommender_award,
          recommender_award: this.defaultSku.recommender_award,
          is_default: 1,
          img_srcs: this.defaultSku.img_srcs,
          title: this.defaultSku.title
        });
      }
      return skuList;
    },
    initData(goodsRuleValues) {
      const data = goodsRuleValues;
      this.goodsRules = [];
      this.memberPriceMap = {};
      // this.marketPriceMap = {}
      this.priceMap = {};
      this.stockMap = {};
      this.weightMap = {};
      this.alertStockMap = {};
      this.goodsNoMap = {};
      // this.barCodeMap = {}
      this.titleMap = {};
      this.firstRecommenderAwardMap = {};
      this.recommenderAwardMap = {};
      this.shareDiscountMap = {};
      this.coverMap = {};
      this.imgSrcsMap = {};
      if (
        data &&
        data.length === 1 &&
        (data[0].sale_pros === "" || data[0].sale_pros === "{}")
      ) {
        // 没有规格的商品，默认特殊处理
        this.isEditingDefaultSku = true;
        this.defaultSku = data[0];
        return;
      }
      if (!data || data.length === 0) {
        // 新增
        this.isEditingDefaultSku = false;
        this.defaultSku = {
          goods_no: "",
          title: "",
          price: "",
          weight: "",
          stock: "",
          alert_stock: "",
          member_price: "",
          cover: "",
          img_srcs: "",
          first_recommender_award: "",
          recommender_award: "",
          share_discount: ""
        };
      }
      if (data && data.length) {
        const mapData = {};
        data.forEach((d, idx) => {
          let props = d.sale_pros;
          if (props) {
            // for
            props = JSON.parse(props);
            if (!this.goodsRules.length) {
              Object.keys(props).forEach(e => {
                this.goodsRules.push({
                  title: e,
                  inputVisible: false,
                  inputValue: "",
                  items: []
                });
              }); // for rule
            }
            Object.keys(props).forEach(e => {
              const items = this.goodsRules.filter(i => i.title === e)[0].items;
              if (!items.some(el => el.title === props[e])) {
                items.push({
                  title: props[e]
                });
              }
            });
            mapData[JSON.stringify(props)] = d;
          }
        });
        let rowCount = 0;
        for (let i = 0; i < this.goodsRules.length; i++) {
          if (this.goodsRules[i].items.length > 0) {
            if (rowCount === 0) {
              rowCount = 1;
            }
            rowCount *= this.goodsRules[i].items.length;
          }
        }
        const tempArr = [];
        let groupCount = 1; // 分组
        for (let i = 0; i < this.goodsRules.length; i++) {
          const rule = this.goodsRules[i];
          const items = rule.items;
          if (items && items.length) {
            const groupSize = rowCount / groupCount;
            const len = rowCount / items.length / groupCount;
            for (let k = 0; k < groupCount; k++) {
              for (let j = 0; j < items.length; j++) {
                for (let h = 0; h < len; h++) {
                  const idx = k * groupSize + h + j * len;
                  if (!tempArr[idx]) {
                    tempArr[idx] = {};
                  }
                  tempArr[idx][rule.title] = items[j].title;
                }
              }
            }
            groupCount *= items.length;
          }
        }
        tempArr.forEach(el => {
          const key = JSON.stringify(el);
          const d = mapData[key];
          const idx = key;
          if (d) {
            this.stockMap[idx] = d.stock;
            this.weightMap[idx] = d.weight;
            this.coverMap[idx] = d.cover;

            this.alertStockMap[idx] = d.alert_stock;
            this.goodsNoMap[idx] = d.goods_no;
            this.memberPriceMap[idx] = d.member_price;
            this.imgSrcsMap[idx] = d.img_srcs;
            this.priceMap[idx] = d.price;
            this.titleMap[idx] = d.title;
            this.firstRecommenderAwardMap[idx] = d.first_recommender_award;
            this.recommenderAwardMap[idx] = d.recommender_award;
            this.shareDiscountMap[idx] = d.share_discount;
            this.$set(this.defaultMap, key, d.is_default === 1);
            this.$set(this.enabledMap, key, true);
          } else {
            this.$set(this.enabledMap, key, false);
          }
        });
      }
    },
    changeHasPic(item, index) {
      if (item.hasPic) {
        this.goodsRules.forEach((el, idx) => {
          if (idx !== index) {
            el.hasPic = false;
          }
        });
      }
    },
    handleAvatarSuccess(item) {
      return (res, file) => {
        if (res && res.errcode === 0) {
          item.cover = res.data;
        }
      };
    },
    priceIndex(row) {
      const rt = [];
      for (let i = 0; i < row.length; i++) {
        rt.push(row[i].index);
      }
      return rt.join(",");
    },
    addNewGoodRule() {
      if (this.goodsRules.length === 0) {
        this.$emit("hasNewGoodRules");
      }
      this.goodsRules.push({
        title: "",
        // hasPic: false,
        inputVisible: false,
        inputValue: "",
        items: []
      });
      this.$nextTick(_ => {
        this.$refs["goodsRuleInput" + (this.goodsRules.length - 1)][0].focus();
      });
    },

    removeRule(index) {
      this.goodsRules.splice(index, 1);
      if (this.goodsRules.length === 0) {
        this.$emit("hasNoNewGoodRules");
      }
      this.goodsNoMap = {};
      // this.barCodeMap = {}
      this.stockMap = {};
      this.weightMap = {};
      this.priceMap = {};
      this.memberPriceMap = {};
      this.alertStockMap = {};
      // this.marketPriceMap = {}
    },
    handleClose(index, yindex) {
      this.goodsRules[index].items.splice(yindex, 1);
      if (this.goodsRules[index].items.length === 0) {
        this.goodsNoMap = {};
        // this.barCodeMap = {}
        this.stockMap = {};
        this.weightMap = {};
        this.priceMap = {};
        this.memberPriceMap = {};
        this.alertStockMap = {};
        // this.marketPriceMap = {}
      }
    },
    showInput(index) {
      this.goodsRules[index].inputVisible = true;
      // this.$set(this.goodsRules[index],'inputVisible',true);
      this.$nextTick(_ => {
        this.$refs["saveTagInput" + index][0].focus();
      });
    },
    handleUploadCoverSuccess(res) {
      // debugger
      if (res.code === 200) {
        this.goodsCoverData.cover = res.data.url;
      } else {
        this.$message.error(res.msg);
      }
    },

    handleInputConfirm(index) {
      const inputValue = this.goodsRules[index].inputValue;
      if (inputValue) {
        if (this.goodsRules[index].items.some(el => el.title === inputValue)) {
          return;
        }
        this.goodsRules[index].items.push({
          title: inputValue
          // cover: ""
        });
        if (this.goodsRules[index].items.length === 1) {
          this.goodsNoMap = {};
          // this.barCodeMap = {}
          this.stockMap = {};
          this.weightMap = {};
          this.priceMap = {};
          this.coverMap = {};
          this.memberPriceMap = {};
          this.alertStockMap = {};
          // this.marketPriceMap = {}
        }
      }
      this.goodsRules[index].inputVisible = false;
      this.goodsRules[index].inputValue = "";
    }
  }
};
</script>

<style scoped>
.el-tag {
  width: 80px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  display: block;

  position: relative;
}

.el-tag >>> .el-tag__close {
  position: absolute;
  right: 5px;
  top: 7px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.el-tag-wrapper {
  display: inline-block;
  vertical-align: middle;
}

.el-tag-wrapper + .el-tag-wrapper {
  margin-left: 10px;
}

.goods-title {
  padding: 0;
}

.goods-title >>> .el-textarea__inner,
.goods-title >>> .el-input__inner {
  padding: 5px;
}

.avatar-uploader-2 {
  margin-top: 5px;

  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}
.disabled_tr {
  background-color: #eee;
  color: #aaa;
}
.avatar-uploader-3 {
  width: 82px;
  margin-top: 5px;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
}

.avatar {
  width: 80px;
  height: 80px;
  display: block;
}

/* .goods-no {
  border: 1px solid #aaa;
  padding: 4px 6px;
  border-radius: 4px;
} */

.box-card {
  margin-bottom: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.price-and-stock table {
  margin-top: 20px;
  width: 100%;
  border-collapse: collapse;
  text-align: center;
}

.price-and-stock th {
  border: 1px solid #eee;
  padding: 15px 5px;
}

.price-and-stock td {
  border: 1px solid #eee;
  padding: 6px 5px;
}

.numberbox {
  width: 100px;
}

.right-icon {
  float: right;
}

.close-btn {
  cursor: pointer;
  margin-top: 10px;
  font-size: 16px;
}

.close-btn:hover {
  color: #409eff;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.batch {
  background-color: rgba(64, 158, 255, 0.1);
  color: #409eff;
}
</style>
